package com.huamao.zh.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huamao.zh.mapper.AccountMapper;
import com.huamao.zh.mapper.DateMapper;
import com.huamao.zh.mapper.GoodsMapper;
import com.huamao.zh.mapper.GoodsSpecsMapper;
import com.huamao.zh.mapper.LogScoreMapper;
import com.huamao.zh.mapper.OrderGoodsMapper;
import com.huamao.zh.mapper.OrdersExtensionMapper;
import com.huamao.zh.mapper.OrdersMapper;
import com.huamao.zh.model.OrderGoods;
import com.huamao.zh.model.Orders;
import com.huamao.zh.model.OrdersExtension;
import com.huamao.zh.model.SKDate;
import com.huamao.zh.service.OrdersAutomaticReceiptService;

@Service
@Transactional
public class OrdersAutomaticReceiptServiceImpl implements OrdersAutomaticReceiptService {

	@Autowired
	private OrdersMapper ordersMapper;

	@Autowired
	private OrdersExtensionMapper ordersExtensionMapper;

	@Autowired
	private DateMapper dateMapper;

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private LogScoreMapper logScoreMapper;

	@Autowired
	private OrderGoodsMapper orderGoodsMapper;

	@Autowired
	private GoodsSpecsMapper goodsSpecsMapper;
	@Autowired
	private GoodsMapper goodsMapper;

	/**
	 * @desc 商城订单自动收货
	 * @author lsx
	 * @date 2017-11-29
	 * @throws Exception
	 */
	@Override
	public void OrdersAutomaticReceipt() throws Exception {
		String remark = "商城订单自动收货";
		// LogUtil.info(LogCodeType.CODE_6006, remark + "开始");
		synchronized (this.getClass()) {
			try {
				Map<String, Object> map = new HashMap<>();
				map.put("orderStatus", 1); // 配送中
				map.put("isPay", 1); // 已支付
				// LogUtil.info(LogCodeType.CODE_6006, "map ：" +
				// JSON.toJSONString(map));
				// 用户支付成功5个工作日后没有主动收货的集合
				List<Orders> overReceiptTimeList = ordersMapper.overReceiptTime(map);
				// LogUtil.info(LogCodeType.CODE_6006,
				// "用户支付成功5个工作日后没有主动收货的集合 ：overReceiptTimeList : " +
				// JSON.toJSONString(overReceiptTimeList));
				if (overReceiptTimeList.size() == 0) {
					return;
				}

				Integer isAutoTake = 0; // 没有自动收货
				List<OrdersExtension> ordersExtensionList = ordersExtensionMapper.getAllNoAutoTake(isAutoTake);
				if (ordersExtensionList.size() == 0) {
					return;
				}
				// LogUtil.info(LogCodeType.CODE_6006,
				// "用户支付成功5个工作日后没有主动收货的集合 ：ordersExtensionList : " +
				// JSON.toJSONString(ordersExtensionList));

				Date date = new Date();
				Date fiftenWorkingDays = fiftenWorkingDaysBefore(date);
				// LogUtil.info(LogCodeType.CODE_6006, "当前时间 ：date : " +
				// JSON.toJSONString(date));
				// LogUtil.info(LogCodeType.CODE_6006,
				// "当前时间加上15个工作日 ：fiftenWorkingDays : " +
				// JSON.toJSONString(fiftenWorkingDays));

				for (Orders orders : overReceiptTimeList) {

					orders.setOrderStatus(3); // 系统确认收货
					orders.setReceiveTime(date); // 收货时间
					ordersMapper.updateSelective(orders);
					// LogUtil.info(LogCodeType.CODE_6006, "orders: " +
					// JSON.toJSONString(orders));

					// 增加销量
					try {
						OrderGoods orderGoods = orderGoodsMapper.getByOrderId(orders.getOrderId());
						// LogUtil.info(LogCodeType.CODE_6006, "orderGoods: " +
						// JSON.toJSONString(orderGoods));
						Map<String, Object> updateMap = new HashMap<>();
						updateMap.put("goodsId", orderGoods.getGoodsId());
						updateMap.put("saleNum", orderGoods.getGoodsNum());
						// LogUtil.info(LogCodeType.CODE_6006, "updateMap: " +
						// JSON.toJSONString(updateMap));
						goodsMapper.updateSaleNum(updateMap);
						if (Integer.parseInt(orderGoods.getGoodsSpecId()) > 0) {
							updateMap.put("goodsSpecId", orderGoods.getGoodsSpecId());
							// LogUtil.info(LogCodeType.CODE_6006, "updateMap: "
							// + JSON.toJSONString(updateMap));
							goodsSpecsMapper.updateSaleNum(updateMap);
						}
					} catch (Exception e) {
					}

					for (OrdersExtension ordersExtension : ordersExtensionList) {

						if (ordersExtension.getOrderId().equals(orders.getOrderId().toString())) {

							ordersExtension.setIsAutoTake(1); // 是否自动收货
							if ("1".equals(ordersExtension.getScoreFlag().toString())) {
								ordersExtension.setSettleTime(date); // 应结算为当前时间
								// 奖励积分
								// rewardScore(orders,ordersExtension,date);
							}
							if ("2".equals(ordersExtension.getScoreFlag().toString())) {
								ordersExtension.setSettleTime(fiftenWorkingDays); // 应结算为当前时间加上15个工作日
							}
							ordersExtensionMapper.updateSelective(ordersExtension);
							// LogUtil.info(LogCodeType.CODE_6006,
							// "ordersExtension: " +
							// JSON.toJSONString(ordersExtension));

						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			// LogUtil.info(LogCodeType.CODE_6006, remark + "结束");
		}
	}

	/**
	 * @desc 奖励积分
	 * @author lsx
	 * @param orders,ordersExtension,date
	 *//*
		 * public void rewardScore(Orders orders, OrdersExtension
		 * ordersExtension,Date date) { LogUtil.info(LogCodeType.CODE_6006,
		 * " 奖励积分开始 ：orders  " + JSON.toJSONString(orders)+"ordersExtension  " +
		 * JSON.toJSONString(ordersExtension)+"date  " +
		 * JSON.toJSONString(date)); Integer UserId = orders.getUserId();
		 * BigDecimal score = ordersExtension.getScore(); Map<String,Object>
		 * updateMap = new HashMap<>(); updateMap.put("UserId",UserId);
		 * updateMap.put("score",score); Account account =
		 * accountMapper.getByUsersId(UserId);
		 * LogUtil.info(LogCodeType.CODE_6006, "奖励积分 account : "
		 * +JSON.toJSONString(account)); LogUtil.info(LogCodeType.CODE_6006,
		 * "奖励积分 updateMap : "+JSON.toJSONString(updateMap));
		 * accountMapper.updateScoreAndTotalScore(updateMap); //积分流水 LogScore
		 * logScore = new LogScore(); logScore.setType(1); //商城消费获取
		 * logScore.setFromId(UserId); logScore.setUserId(UserId);
		 * logScore.setOrderNo(ordersExtension.getOrderId());
		 * logScore.setPreScore(account.getScore()); logScore.setScoreType(1);
		 * logScore.setScore(score); logScore.setRemark("商城消费获取");
		 * logScore.setDataFlag(1); logScore.setCreateTime(date);
		 * LogUtil.info(LogCodeType.CODE_6006, "奖励积分 logScore : "
		 * +JSON.toJSONString(logScore)); logScoreMapper.add(logScore);
		 * LogUtil.info(LogCodeType.CODE_6006, " 奖励积分结束"); }
		 */
	/**
	 * @desc 当前时间加上15个工作日
	 * @author lsx
	 * @return date
	 * @param date
	 * @throws Exception
	 */
	public Date fiftenWorkingDaysBefore(Date date) throws Exception {

		Calendar calendar = Calendar.getInstance(); // 得到日历
		calendar.setTime(date);// 把当前时间赋给日历
		int fiftenWorkingDays = 0;

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String DateFormat = simpleDateFormat.format(calendar.getTime());

		List<SKDate> skDates = dateMapper.queryList(null);
		SKDate skDate = null;
		for (SKDate SKDate : skDates) {
			if (DateFormat.equals(SKDate.getDate().toString())) {
				skDate = SKDate;
			}
		}

		List<SKDate> SkDatesChliden = skDates.subList(skDates.indexOf(skDate), skDates.size());

		for (SKDate skDateChliden : SkDatesChliden) {
			if (skDateChliden.getStatus() == 0) {
				fiftenWorkingDays = fiftenWorkingDays + 1;
			}
			if (fiftenWorkingDays == 15) {
				skDate = skDateChliden;
				break;
			}
		}

		List<SKDate> SkDatesList = SkDatesChliden.subList(SkDatesChliden.indexOf(skDate), SkDatesChliden.size());

		skDate = SkDatesList.get(0);
		String stringDate = skDate.getDate().toString();
		String year = stringDate.substring(0, 4);
		String month = stringDate.substring(4, 6);
		String day = stringDate.substring(6, 8);

		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
		Date fiftenWorkingDate = simpleDate.parse(year + "-" + month + "-" + day);

		return fiftenWorkingDate;

	}

}
